﻿using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using Edu.Web.Data;
using Edu.Web.Data.DAO;
using Edu.Web.Data.DAO.Impl;
using Edu.Web.Data.Service;
using Edu.Web.Data.Service.Impl;
using ESoft.Core.Data;
using ESoft.Core.Initialize;
using ESoft.Core.Interceptor;
using ESoft.Core.Logging;
using ESoft.Core.Logging.Log4Net;
using ESoft.Core.Model;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using WebAPiDEMO.Models;

namespace WebAPiDEMO
{
    public class Startup
    {
        private const string SecretKey = "need_to_get_this_from_enviroment";
        private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        public IContainer ApplicationContainer { get; private set; }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();
            app.UseMvc();

            DatabaseInitialize();
            LoggingInitialize();

        }

        private static void DatabaseInitialize()
        {
            var assmblyArr = typeof(Startup).Assembly;
            DatabaseInitializer.AddMapperAssembly(assmblyArr);
            DatabaseInitializer.Initialize();
        }

        private static void LoggingInitialize()
        {
            Log4NetLoggerAdapter adapter = new Log4NetLoggerAdapter();
            LogManager.AddLoggerAdapter(adapter);
        }

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                       .AddJwtBearer(options =>
                       {
                           options.TokenValidationParameters = new TokenValidationParameters
                           {
                               ValidateIssuer = true,
                               ValidateAudience = true,
                               ValidateLifetime = true,
                               ValidateIssuerSigningKey = true,
                               ValidIssuer = Configuration["Jwt:Issuer"],
                               ValidAudience = Configuration["Jwt:Issuer"],
                               IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                           };
                       });

            services.AddMvc();


            //Now register our services with Autofac container
            var builder = new ContainerBuilder();

            builder.RegisterType<TransactionInterceptor>();
            builder.RegisterType<EduContextOption>().As<IDbContextOption>().WithProperty("Connetion", Configuration.GetConnectionString("ConnectionStrings"));
            builder.RegisterType<NoticeService>().As<INoticeService>();


            var assmblyArr = typeof(Startup).Assembly;

            builder.RegisterAssemblyTypes(assmblyArr).Where(t => t.Name.EndsWith("DAO")).AsImplementedInterfaces().EnableInterfaceInterceptors().InterceptedBy(typeof(TransactionInterceptor));


            builder.RegisterAssemblyTypes(assmblyArr)
                .Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces()
                .EnableInterfaceInterceptors().InterceptedBy(typeof(TransactionInterceptor));

            //builder.RegisterType<SiteAnalyticsServices>();
            builder.Populate(services);
            this.ApplicationContainer = builder.Build();
            //Create the IServiceProvider based on the container.
            return new AutofacServiceProvider(ApplicationContainer);
        }
    }
}
